﻿using SqlSugar;
using System.Data;

namespace AuthServer.Utility.InitDatabaseExt
{
    /// <summary>
    /// 初始化SqlSugar
    /// </summary>
    public static class InitSqlSugarExt
    {
        /// <summary>
        /// 初始化SqlSugar
        /// </summary>
        /// <param name="builder"></param>
        public static void InitSqlSugar(this WebApplicationBuilder builder)
        {
          

            builder.Services.AddScoped<ISqlSugarClient>(s =>
            {
                ConnectionConfig connection = new ConnectionConfig()
                {
                    ConnectionString = @"DataSource=D:\data.db3",
                    DbType = SqlSugar.DbType.Sqlite,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                   
                };
                SqlSugarClient client = new SqlSugarClient(connection);
                client.Aop.OnLogExecuting = (s, p) =>
                {
                    Console.WriteLine($"OnLogExecuting:输出Sql语句:{s} || 参数为：{string.Join(",", p.Select(p => p.Value))}");
                };
                client.Aop.OnExecutingChangeSql = (s, p) =>
                {
                    Console.WriteLine($"OnLogExecuting:输出Sql语句:{s} || 参数为：{string.Join(",", p.Select(p => p.Value))}");
                    return new KeyValuePair<string, SugarParameter[]>(s, p);
                };
                client.Aop.OnLogExecuted = (s, p) =>
                {
                    Console.WriteLine($"OnLogExecuted:输出Sql语句:{s} || 参数为：{string.Join(",", p.Select(p => p.Value))}");
                };
                client.Aop.OnError = e =>
                {
                    Console.WriteLine($"OnError:Sql语句执行异常:{e.Message}");
                };

                //////查询过滤器
                //client.QueryFilter.AddTableFilter<Sys_Menu>(it => it.IsDeleted == false);
                //client.QueryFilter.AddTableFilter<Sys_Role>(it => it.IsDeleted == false);
                //client.QueryFilter.AddTableFilter<Sys_RoleMenuMap>(it => it.IsDeleted == false);
                //client.QueryFilter.AddTableFilter<Sys_User>(it => it.IsDeleted == false);
                //client.QueryFilter.AddTableFilter<Sys_UserRoleMap>(it => it.IsDeleted == false);

                return client;
            });
        }
    }
}
